package com.web.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.dto.RankDTO;
import com.common.entity.Developer;
import com.common.util.DeveloperConverter;
import com.common.vo.DeveloperVO;
import com.web.mapper.DeveloperMapper;
import com.web.service.FormatDeveloper;
import com.web.service.RankModel;
import io.github.coho04.githubapi.Github;
import io.github.coho04.githubapi.entities.GHUser;
import io.github.coho04.githubapi.entities.repositories.GHRepository;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.common.constant.Token.GITHUB_API_URL;
import static com.common.constant.Token.GITHUB_TOKEN;

/**
 * GithubAPI接口调用
 */
@Service
public class FormatDeveloperImpl implements FormatDeveloper {

    @Autowired
    private DeveloperMapper developerMapper;

    @Autowired
    private RankModel rankModel;

    /**
     * 获取Developer，进行评估，插入数据库
     *
     * @param userName
     * @return
     */
    public DeveloperVO handle(String userName){

        // 构建完整的 URL
        String url = GITHUB_API_URL + userName;

        // 使用 Hutool 发起 GET 请求
        HttpResponse response = HttpRequest.get(url)
                .header("Authorization", "token " + GITHUB_TOKEN)  // 设置 GitHub Token 以避免限流
                .header("Accept", "application/vnd.github.v3+json")  // 设置接受的数据格式
                .timeout(20000)  // 设置超时时间（毫秒）
                .execute();

        //username不存在的情况
        if (response.getStatus() == 404) {
            // 处理用户名不存在的情况
            System.out.println("用户不存在，返回的信息为: " + response.body());
            return null;
        }

        //过滤有用的数据
        Developer developer = JSON.parseObject(response.body(), Developer.class);
        developer.setUserName(userName);
        cleanUrls(developer);

        //获取具体缺失的参数
        developer = rankModel.calulateParameter(developer);

        //计算评估
        RankDTO rankDTO = rankModel.calculateRank(developer);

        developer.setPercentile(rankDTO.getPercentile());
        developer.setLevel(rankDTO.getLevel());

        //插入数据库
        developerMapper.insert(developer);

        return DeveloperConverter.convertToVO(developer);
    }


    // 清理 URL{}
    private Developer cleanUrls(Developer developer) {
        developer.setFollowersUrl(cleanUrl(developer.getFollowersUrl()));
        developer.setFollowingUrl(cleanUrl(developer.getFollowingUrl()));
        developer.setGistsUrl(cleanUrl(developer.getGistsUrl()));
        developer.setStarredUrl(cleanUrl(developer.getStarredUrl()));
        developer.setReposUrl(cleanUrl(developer.getReposUrl()));
        developer.setEventsUrl(cleanUrl(developer.getEventsUrl()));
        developer.setReceivedEventsUrl(cleanUrl(developer.getReceivedEventsUrl()));
        return developer;
    }

    // 辅助方法，用于清理 URL
    private String cleanUrl(String url) {
        if (url != null) {
            return url.replaceAll("\\{.*?\\}", ""); // 去掉花括号及其内容
        }
        return null;
    }
}
